import psycopg2
from datetime import datetime

DB_CONFIG = {
    "dbname": "game_trading_v2",
    "user": "postgres",
    "password": "145114",
    "host": "localhost",
    "port": "5432"
}

def get_conn():
    return psycopg2.connect(**DB_CONFIG)

def deposit(user_id, amount):
    """
    充值：使用deposit_funds存储过程增加用户余额并记录充值流水
    """
    if amount <= 0:
        return False, "充值金额必须大于0"
    
    conn = get_conn()
    cur = conn.cursor()
    try:
        # 创建临时表存储结果
        cur.execute("""
            CREATE TEMP TABLE deposit_result (
                success BOOLEAN,
                message TEXT
            )
        """)
        
        # 调用存储过程并获取OUT参数
        cur.execute("""
            DO $$
            DECLARE
                success_out BOOLEAN;
                message_out TEXT;
            BEGIN
                CALL deposit_funds(%s, %s, success_out, message_out);
                INSERT INTO deposit_result VALUES (success_out, message_out);
            END $$;
        """, (user_id, amount))
        
        # 获取存储过程的结果
        cur.execute("SELECT * FROM deposit_result")
        result = cur.fetchone()
        
        if result:
            success = result[0]  # 第一列是success
            message = result[1]  # 第二列是message
            
            conn.commit()
            return success, message
        else:
            conn.rollback()
            return False, "充值处理失败，未返回结果"
            
    except Exception as e:
        conn.rollback()
        return False, f"充值失败: {e}"
    finally:
        # 清理临时表
        try:
            cur.execute("DROP TABLE IF EXISTS deposit_result")
        except:
            pass
        cur.close()
        conn.close()

def withdraw(user_id, amount):
    """
    提现：使用withdraw_funds存储过程减少用户余额并记录提现流水
    """
    if amount <= 0:
        return False, "提现金额必须大于0"
    
    conn = get_conn()
    cur = conn.cursor()
    try:
        # 创建临时表存储结果
        cur.execute("""
            CREATE TEMP TABLE withdraw_result (
                success BOOLEAN,
                message TEXT
            )
        """)
        
        # 调用存储过程并获取OUT参数
        cur.execute("""
            DO $$
            DECLARE
                success_out BOOLEAN;
                message_out TEXT;
            BEGIN
                CALL withdraw_funds(%s, %s, success_out, message_out);
                INSERT INTO withdraw_result VALUES (success_out, message_out);
            END $$;
        """, (user_id, amount))
        
        # 获取存储过程的结果
        cur.execute("SELECT * FROM withdraw_result")
        result = cur.fetchone()
        
        if result:
            success = result[0]  # 第一列是success
            message = result[1]  # 第二列是message
            
            conn.commit()
            return success, message
        else:
            conn.rollback()
            return False, "提现处理失败，未返回结果"
            
    except Exception as e:
        conn.rollback()
        return False, f"提现失败: {e}"
    finally:
        # 清理临时表
        try:
            cur.execute("DROP TABLE IF EXISTS withdraw_result")
        except:
            pass
        cur.close()
        conn.close()